package org.springblade.modules.admin.service.feishu.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.feishu.FeiShuUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.RepeatFaultElevatorListDTO;
import org.springblade.modules.admin.dto.RepeatFaultPlanListDTO;
import org.springblade.modules.admin.entity.feishu.LarkFaultRiskTemplateContent;
import org.springblade.modules.admin.entity.feishu.LarkFaultRiskTemplateHeader;
import org.springblade.modules.admin.entity.feishu.LarkFaultRiskTemplateMarkDownContent;
import org.springblade.modules.admin.enums.ElevatorFaultLevelEnum;
import org.springblade.modules.admin.service.UserExtService;
import org.springblade.modules.admin.service.feishu.ILarkFaultRiskMessageService;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author: Sharry
 * @createTime: 2025-02-25 19:24
 * @version: Version-1.0
 */
@Service
@Slf4j
public class LarkFaultRiskMessageServiceImpl implements ILarkFaultRiskMessageService {

	@Autowired
	private FeiShuUtil feishuUtil;

	@Autowired
	private UserExtService userExtService;

	@Autowired
	private IDictService dictService;

	/**
	 * 2025-02-26 故障风险等级
	 *
	 * @param level     风险等级
	 * @param paramList DTO列表
	 */
	@Override
	public void sendLarkFaultRiskMessage(Integer level, List<RepeatFaultPlanListDTO> paramList) {
		if (level < 1 || level > 6) {
			throw new ServiceException("风险等级传参错误，请检查");
		}
		if (Func.isEmpty(paramList)) {
			return;
		}
		if(level == 6){
			log.info("风险等级为6，不发送消息");
			return;
		}
		// 1. 定义固定推送人员
//		正式环境
		List<String> targetUserList = getTargetUserListProd(level);
		// 测试/开发环境
//		List<String> targetUserList = getTargetUserListTest(level);

		// 2.对五级人员进行单独卡片组装与推送
		if(level == 5) {
			Map<String, List<RepeatFaultPlanListDTO>> levelFiveMap = new HashMap<>();
			paramList.forEach(p -> {
				Long elevatorId = p.getElevatorId();
				// 根据梯id查询维保组长飞书id
				List<String> groupManagerLarkId = userExtService.getLarkIdByElevatorId(elevatorId);
				// 当为空的情况
				if (Func.isEmpty(groupManagerLarkId)) {
					log.warn("维保组长飞书id为空，请检查，触发电梯id为：{}", elevatorId);
					return;
				}
				groupManagerLarkId.forEach(g -> {
					if (levelFiveMap.containsKey(g)) {
						levelFiveMap.get(g).add(p);
					} else {
						List<RepeatFaultPlanListDTO> list = new ArrayList<>();
						list.add(p);
						levelFiveMap.put(g, list);
					}
				});
			});
			// 给五级人员推送
			if (Func.isNotEmpty(levelFiveMap)) {
				levelFiveMap.forEach((k, v) -> {
					List<String> levelFiveUserIdList = new ArrayList<>();
					levelFiveUserIdList.add(k);
					sendRiskLevelCardMessage(level,levelFiveUserIdList, v);
				});
			}
		}
		// 固定推送人员推送
		sendRiskLevelCardMessage(level,targetUserList, paramList);
	}

	@Override
	public List<String> getLarkUserIdByLevel(Integer level) {
		return getTargetUserListProd(level);
	}

	/**
	 * 根据等级获取目标推送对象，以及封装固定对象
	 *
	 * @return 目标推送静态对象列表
	 */
	private List<String> getTargetUserListProd(Integer level) {
		if(Func.isNull(level)){
			throw new ServiceException("通过风险等级获取飞书推送人员id，风险等级不能为空");
		}
		List<String> targetUserList = new ArrayList<>();
		// 通过dict获取对应等级的飞书id
		if(level == 1){
			List<Dict> larkone = dictService.list(new LambdaQueryWrapper<Dict>()
				.eq(Dict::getCode, "larkone")
				.eq(Dict::getIsDeleted, 0)
				.ne(Dict::getParentId, 0)
			);
			if(Func.isNotEmpty(larkone)){
				larkone.stream().map(Dict::getDictKey).forEach(targetUserList::add);
			}
			return targetUserList;
		}
		if(level == 2){
			List<Dict> larktwo = dictService.list(new LambdaQueryWrapper<Dict>()
				.eq(Dict::getCode, "larktwo")
				.eq(Dict::getIsDeleted, 0)
				.ne(Dict::getParentId, 0)
			);
			if(Func.isNotEmpty(larktwo)){
				larktwo.stream().map(Dict::getDictKey).forEach(targetUserList::add);
			}
			return targetUserList;
		}
		if(level == 3){
			List<Dict> larkthree = dictService.list(new LambdaQueryWrapper<Dict>()
				.eq(Dict::getCode, "larkthree")
				.eq(Dict::getIsDeleted, 0)
				.ne(Dict::getParentId, 0)
			);
			if(Func.isNotEmpty(larkthree)){
				larkthree.stream().map(Dict::getDictKey).forEach(targetUserList::add);
			}
			return targetUserList;
		}
		if(level == 4){
			List<Dict> larkfour = dictService.list(new LambdaQueryWrapper<Dict>()
				.eq(Dict::getCode, "larkfour")
				.eq(Dict::getIsDeleted, 0)
				.ne(Dict::getParentId, 0)
			);
			if(Func.isNotEmpty(larkfour)){
				larkfour.stream().map(Dict::getDictKey).forEach(targetUserList::add);
			}
			return targetUserList;
		}
		return targetUserList;
	}

	/**
	 * 测试/开发环境获取静态对象列表
	 */
	private List<String> getTargetUserListTest(Integer level) {
		// 以下是开发/测试环境levelUserIdMap,发送给自己人
		List<String> levelOneAndTwo = new ArrayList<>();
		// 明君、天雄
		levelOneAndTwo.add("54666354");
		levelOneAndTwo.add("9d933gb9");
		// 三级  璟哥
		List<String> levelThree = new ArrayList<>();
		levelThree.add("1878gea9");
		// 四级 远哥
		List<String> levelFour = new ArrayList<>();
//		levelFour.add("3dg996ag");
		// 五级 Sharry、远哥
		List<String> levelFive = new ArrayList<>();
		levelFive.add("59e242de");
		levelFive.add("3dg996ag");
        List<String> targetUserList = new ArrayList<>();

		// 规则： 一二级：全部
		if(level <= 2){
			targetUserList.addAll(levelOneAndTwo);
			return targetUserList;
		}
		// 规则：三：三、四级
		if (level == 3){
			targetUserList.addAll(levelThree);
			return targetUserList;
		}
		// 规则：四：四级， 以及拼接通过梯id查询维保组长
		if (level == 4){
			targetUserList.addAll(levelFour);
			return targetUserList;
		}
//		if (level == 5){
//			targetUserList.addAll(levelFive);
//			return targetUserList;
//		}
		return targetUserList;
	}

	/**
	 * 根据 userIdList 与 List<RepeatFaultPlanListDTO> paramList 组装卡片并发送消息
	 */
	private void sendRiskLevelCardMessage(Integer level,List<String> userIdList, List<RepeatFaultPlanListDTO> paramList){
		// 当 paramList 为空时，不发送消息
		if(Func.isEmpty(paramList) || Func.isEmpty(userIdList)){
			return;
		}

		LarkFaultRiskTemplateHeader header = new LarkFaultRiskTemplateHeader();
		String headerFormat = header.getHeader();
		// 获取当前日期，并格式化成 yyyy/MM/dd
		String currentDate = DateUtil.format(DateUtil.now(), "yyyy/MM/dd HH:mm:ss");
		String headerContent = String.format(headerFormat, currentDate);
		// 组装卡片内容
		String tempMarkDownContent = "";
		// 根据 风险等级 正序排序
		paramList.sort(Comparator.comparing(RepeatFaultPlanListDTO::getFaultLevel));

		// 截取前10条数据
		if(paramList.size() > 10){
			paramList = paramList.subList(0, 10);
		}

		for (int i = 0; i < paramList.size(); i++) {
			RepeatFaultPlanListDTO f = paramList.get(i);
			Date planCreateTime = f.getCreateTime();
			String planCreateTimeDesc = DateUtil.format(planCreateTime, "yyyy/MM/dd HH:mm:ss");
			LarkFaultRiskTemplateMarkDownContent markDownContent = new LarkFaultRiskTemplateMarkDownContent();
			String markdown = markDownContent.getMarkdown();
            String indexValue = String.valueOf(i + 1);
			String contentFormat = String.format(markdown,
				indexValue,
				f.getElevatorAddress(),
				f.getLevelDesc(),
				f.getBuildingName(),
				f.getFaultLabel(),
				planCreateTimeDesc,
				f.getPlanStatusDesc(),
				f.getPlanUserName(),
				f.getFaultOverTimeDesc(),
				f.getIsRole());
			tempMarkDownContent += contentFormat;
		}

		LarkFaultRiskTemplateContent content = new LarkFaultRiskTemplateContent();
		String contentResult = content.getContent();
		String levelDesc = ElevatorFaultLevelEnum.getStatusDescListByLevel(level);
		// 获取当前启动的是dev还是prod环境
		String activeProfile = System.getProperty("spring.profiles.active");
		String urlFormat = "";
		if("prod".equals(activeProfile)){
			urlFormat = "https://admin.sida-tech.com/#/list?level=" + levelDesc;
		}else{
			urlFormat = "https://admin-test.sida-tech.com/#/list?level=" + levelDesc;
		}

		contentResult = String.format(contentResult,
			tempMarkDownContent,
			urlFormat,
			urlFormat,
			urlFormat,
			urlFormat);

		String finalContent = contentResult + headerContent;
		userIdList.forEach(u -> feishuUtil.sendLarkMessageByUserId(u, finalContent));
	}

}
